package com.liang.recommend.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

@Configuration
public class RedisConfig {

    //自己定义了一个RedisTemplate
    //开箱即用！
    @Bean("s")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        //我们为了自己开发方便，一般直接使用string object类型
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        //配置具体的序列化方式
        //json解析所有对象
        Jackson2JsonRedisSerializer<Object> serializerJson = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializerJson.setObjectMapper(mapper);
        //String的序列化
        StringRedisSerializer serializerString = new StringRedisSerializer();
        //key序列化采用string
        template.setKeySerializer(serializerString);
        //hash的key序列化采用string
        template.setHashKeySerializer(serializerString);
        //value序列化采用jackson
        template.setValueSerializer(serializerJson);
        //hash的value序列化采用jackson
        template.setHashValueSerializer(serializerJson);
        template.afterPropertiesSet();
        return template;
    }

}
